/*
** plsp.c for  in /home/lucas/projet/philosophe/laidfilauxzauphe
** 
** Made by Lucas Stefas
** Login   <stefas_l@epitech.net>
** 
** Started on  Sat Apr 30 10:06:37 2011 Lucas Stefas
** Last update Sat Apr 30 10:09:45 2011 Lucas Stefas
*/

#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include "plsp.h"

baguette	**creatbaguettes(int i)
{
  baguette**	baguettes;

  baguettes = malloc(sizeof(baguette*) * i);
  while (--i > -1)
    {
      baguettes[i] = new_baguette(i);
      printf("baguette %d created.\n", baguettes[i]->id);
    }
  return (baguettes);
}





philosophe	**creatph(int i, table *table, philosophe **philosophes)
{
  while (--i > -1)
    {
      philosophes[i] = new_philosophe(i, table);
      pthread_create(&philosophes[i]->thread, NULL,
		     run_philosophe, (void*)philosophes[i]);
    }
  return (philosophes);
}

int		main()
{
  philosophe**	philosophes;
  baguette**	baguettes;
  table*	tables;
  nbtruc	n = parseur("philosophes.xml");
  int		i;

  baguettes = creatbaguettes(n.nbbaguette);
  tables = new_table(baguettes, n.nbbaguette);
  philosophes = malloc(sizeof(philosophe*) * n.nbphilosophe);
  pthread_mutex_lock(&tables->starter);
  philosophes = creatph(n.nbphilosophe, tables, philosophes);
  i = n.nbphilosophe;
  printf("Now they can run !\n");
  pthread_mutex_unlock(&tables->starter);
  pthread_mutex_unlock(&tables->looker);
  while (--i > -1)
    pthread_join(philosophes[i]->thread, NULL);
  return (0);
}
